<!DOCTYPE html><html lang="en" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>Java 中 IO 操作总结 | Lorem MoonのStory</title><meta name="keywords" content="Java"><meta name="author" content="Lorem Moon"><meta name="copyright" content="Lorem Moon"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="java IO 操作分析直接看代码吧 package jdk.util.sourceCode;import java.io.*;&#x2F;** * 经常会遇到各种 IO 流操作，IO 流操作一般分为两类：字符流和字节流。 * 以 &quot;Reader&quot; 结尾都是字符流，操作的都是字符型的数据 * 以 &quot;Stream&quot; 结尾的都是字节流，操作的都是 byte 类型的数据 *">
<meta property="og:type" content="article">
<meta property="og:title" content="Java 中 IO 操作总结">
<meta property="og:url" content="https://hello-github-ui.github.io/posts/65533/index.html">
<meta property="og:site_name" content="Lorem MoonのStory">
<meta property="og:description" content="java IO 操作分析直接看代码吧 package jdk.util.sourceCode;import java.io.*;&#x2F;** * 经常会遇到各种 IO 流操作，IO 流操作一般分为两类：字符流和字节流。 * 以 &quot;Reader&quot; 结尾都是字符流，操作的都是字符型的数据 * 以 &quot;Stream&quot; 结尾的都是字节流，操作的都是 byte 类型的数据 *">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="https://img.imgdb.cn/item/604b7e335aedab222ce6192e.jpg">
<meta property="article:published_time" content="2020-01-05T19:35:31.000Z">
<meta property="article:modified_time" content="2022-03-08T12:34:42.570Z">
<meta property="article:author" content="Lorem Moon">
<meta property="article:tag" content="Java">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img.imgdb.cn/item/604b7e335aedab222ce6192e.jpg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://hello-github-ui.github.io/posts/65533/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: {"appId":"D5QZVMNT9K","apiKey":"92de0b03da46fa778c95817524081160","indexName":"hexo-blog","hits":{"per_page":100},"languages":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}.","hits_stats":"${hits} results found in ${time} ms"}},
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: {"limitDay":365,"position":"top","messagePrev":"It has been","messageNext":"days since the last update, the content of the article may be outdated."},
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":200},
  copy: {
    success: 'Copy successfully',
    error: 'Copy error',
    noSupport: 'The browser does not support'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: 'days',
  date_suffix: {
    just: 'Just',
    min: 'minutes ago',
    hour: 'hours ago',
    day: 'days ago',
    month: 'months ago'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Java 中 IO 操作总结',
  isPost: true,
  isHome: false,
  isHighlightShrink: true,
  isToc: true,
  postUpdate: '2022-03-08 20:34:42'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 5.4.0"></head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://pic.imgdb.cn/item/6159d89b2ab3f51d91b0e8d0.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data is-center"><div class="data-item"><a href="/archives/"><div class="headline">Articles</div><div class="length-num">60</div></a></div><div class="data-item"><a href="/tags/"><div class="headline">Tags</div><div class="length-num">46</div></a></div><div class="data-item"><a href="/categories/"><div class="headline">Categories</div><div class="length-num">5</div></a></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> Home</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> Archives</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> Tags</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> Categories</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> List</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/musics/"><i class="fa-fw fas fa-music"></i><span> Music</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> Movie</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> Link</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> About</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://img.imgdb.cn/item/604b7e335aedab222ce6192e.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">Lorem MoonのStory</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> Search</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> Home</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> Archives</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> Tags</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> Categories</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> List</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/musics/"><i class="fa-fw fas fa-music"></i><span> Music</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> Movie</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> Link</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> About</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Java 中 IO 操作总结<a class="post-edit-link" href="https://github.com/hello-github-ui/hexo-blog-source/tree/master/source/_posts/Java-中-IO-操作总结.md" title="Edited on" target="_blank"><i class="fas fa-pencil-alt"></i></a></h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">Created</span><time class="post-meta-date-created" datetime="2020-01-05T19:35:31.000Z" title="Created 2020-01-06 03:35:31">2020-01-06</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">Updated</span><time class="post-meta-date-updated" datetime="2022-03-08T12:34:42.570Z" title="Updated 2022-03-08 20:34:42">2022-03-08</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/code/">code</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">Word count:</span><span class="word-count">1.9k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">Reading time:</span><span>7min</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Java 中 IO 操作总结"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">Post View:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="java-IO-操作分析"><a href="#java-IO-操作分析" class="headerlink" title="java IO 操作分析"></a><font color=#FF8C00>java IO 操作分析</font></h1><p>直接看代码吧</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">package</span> jdk.util.sourceCode;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.*;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 经常会遇到各种 IO 流操作，IO 流操作一般分为两类：字符流和字节流。</span></span><br><span class="line"><span class="comment"> * 以 &quot;Reader&quot; 结尾都是字符流，操作的都是字符型的数据</span></span><br><span class="line"><span class="comment"> * 以 &quot;Stream&quot; 结尾的都是字节流，操作的都是 byte 类型的数据</span></span><br><span class="line"><span class="comment"> * 二者的区别：</span></span><br><span class="line"><span class="comment"> *  字节流没有缓冲区，是直接输出的；而字符流是先输出到缓冲区，然后在调用 close() 方法后再输出信息</span></span><br><span class="line"><span class="comment"> *  处理对象不同，字节流能处理所有类型的数据，但是字符流只能处理字符类型的数据（只要是处理纯文本数据，就优先考虑使用字符流，除此之外都使用字节流）</span></span><br><span class="line"><span class="comment"> * java byte -&gt; short -&gt; int -&gt; long    1byte -&gt; 2byte -&gt; 4byte -&gt; 8byte</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * InputStream 和 OutputStream 是各种输入输出字节流的基类，所有字节流都继承于这两个基类</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * FileInputStream 和 FileOutputStream 这两个从字面意思很容易理解，是对文件的字节流操作，也是最常见的 IO 操作流</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * 非流式文件类 -- File 类</span></span><br><span class="line"><span class="comment"> *  从定义来看，File 类是 Object 的直接子类，同时它继承了 Comparable 接口可以进行数组的排序</span></span><br><span class="line"><span class="comment"> *  File 类的操作包括文件的创建，删除，重命名，得到文件/文件夹的路径，创建时间等</span></span><br><span class="line"><span class="comment"> *  File 类是对文件系统中文件以及文件夹进行封装的一个对象，可以通过对象的思想来操作文件和文件夹</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> /</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span>: util.you.com@gmail.com</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span>: 2019/5/25 15:40</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@description</span>:</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@version</span>: 1.0</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@className</span>: TestIO</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TestIO</span> </span>&#123;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span>  <span class="title">main</span><span class="params">(String[] args)</span></span>&#123;</span><br><span class="line">        <span class="comment">// 1.调用 新建文件</span></span><br><span class="line"><span class="comment">//        createFile(&quot;F:\\github\\util.you.com@gmail.com\\jdk\\src\\main\\java\\jdk\\util\\sourceCode\\&quot;, &quot;测试io.txt&quot;);</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">// 2.调用删除文件</span></span><br><span class="line"><span class="comment">//        deleteFile(&quot;F:\\github\\util.you.com@gmail.com\\jdk\\src\\main\\java\\jdk\\util\\sourceCode\\&quot;,&quot;测试io.txt&quot;);</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">// 3.调用创建文件夹</span></span><br><span class="line"><span class="comment">//        createFolder(&quot;F:\\github\\util.you.com@gmail.com\\jdk\\src\\main\\java\\jdk\\util\\sourceCode\\&quot;, &quot;测试io文件夹&quot;);</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">// 4.列出指定目录下面的所有文件，包括隐藏文件</span></span><br><span class="line"><span class="comment">//        listFiles(&quot;F:\\github\\util.you.com@gmail.com\\jdk\\src\\main\\java\\jdk\\util\\sourceCode\\&quot;);</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">// 5.判断指定的 文件夹是否是一个 目录(即是否是一个 文件夹)</span></span><br><span class="line"><span class="comment">//        isFolder(&quot;F:\\\\github\\\\util.you.com@gmail.com\\\\jdk\\\\src\\\\main\\\\java\\\\jdk\\\\util\\\\sourceCode\\&quot;, &quot;测试io文件夹&quot;);</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">// 6. 向指定的文件中(需要在文件名中给出路径和文件名,我这里是为了简便这样写了)通过 字节流 写入数据 (这里前提：认为该文件已经存在,不需要再创建)</span></span><br><span class="line"><span class="comment">//        writeFileByByte(&quot;F:\\github\\util.you.com@gmail.com\\jdk\\src\\main\\java\\jdk\\util\\sourceCode\\测试io.txt&quot;);</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">// 7.从指定的文件中读取内容</span></span><br><span class="line"><span class="comment">//        readFileByByte(&quot;F:\\github\\util.you.com@gmail.com\\jdk\\src\\main\\java\\jdk\\util\\sourceCode\\测试io.txt&quot;);</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">// 8. 从 指定文件读取内容并写入到 目标文件</span></span><br><span class="line">        readWriteFile(<span class="string">&quot;F:\\game\\xx.mp4&quot;</span>,</span><br><span class="line">                <span class="string">&quot;E:\\github-project\\jdk\\src\\main\\java\\jdk\\util\\sourceCode\\测试io.txt&quot;</span>);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 因为 io 流基本是与 File(文件/文件夹) 操作密不可分的，因此 io 的操作，只要涉及到文件，文件夹的都必须使用 File 类</span></span><br><span class="line"><span class="comment">     * 在指定的路径下，新建一个 指定文件名的 文件</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> path 文件路径</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> fileName 文件名</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">createFile</span><span class="params">(String path, String fileName)</span></span>&#123;</span><br><span class="line">        <span class="comment">// 因为是在 操作 文件，所以用到 File 对象【记住：所有与文件/文件夹操作相关的内容，都必须第一时间想到要用 File 对象】</span></span><br><span class="line">        File file = <span class="keyword">new</span> File(path+fileName); <span class="comment">// 实例化一个 file 操作对象</span></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            file.createNewFile(); <span class="comment">// 调用 file 文件/文件夹 实例对象的 方法，来新建文件</span></span><br><span class="line">            System.out.println(<span class="string">&quot;目标文件已存在: &quot;</span> + path + fileName);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 删除一个指定路径下的 文件</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> path 该文件的路径</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> fileName 该文件的文件名</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">deleteFile</span><span class="params">(String path, String fileName)</span></span>&#123;</span><br><span class="line">        File file = <span class="keyword">new</span> File(path+fileName);</span><br><span class="line">        <span class="keyword">if</span>(file.exists())&#123;</span><br><span class="line">            file.delete();</span><br><span class="line">            System.out.println(<span class="string">&quot;目标文件已删除&quot;</span>);</span><br><span class="line">        &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;要删除的目标文件不存在&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 新建一个 文件夹</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> path 路径</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> folderName 文件夹名</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">createFolder</span><span class="params">(String path, String folderName)</span></span>&#123;</span><br><span class="line">        File file = <span class="keyword">new</span> File(path+folderName);</span><br><span class="line">        file.mkdir();</span><br><span class="line">        System.out.println(<span class="string">&quot;该文件夹已经存在于: &quot;</span> + path + folderName);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 列出指定目录下面的所有文件</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> path 目录的路径名</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">listFiles</span><span class="params">(String path)</span></span>&#123;</span><br><span class="line">        File file = <span class="keyword">new</span> File(path);</span><br><span class="line">        <span class="keyword">if</span> (file.isDirectory())&#123;</span><br><span class="line">            File[] fileArray = file.listFiles();</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; fileArray.length; i++)&#123;</span><br><span class="line">                System.out.println( <span class="string">&quot;该目录下的文件: &quot;</span> + fileArray[i]);</span><br><span class="line">                System.out.println( <span class="string">&quot;该目录下的文件或文件夹的名字: &quot;</span> + fileArray[i].getName());</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">            System.out.println(path + <span class="string">&quot; 目录不存在&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 判断给定的 文件夹 是否是一个目录</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> path</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">isFolder</span><span class="params">(String path, String folderName)</span></span>&#123;</span><br><span class="line">        File file = <span class="keyword">new</span> File(path + folderName);</span><br><span class="line">        <span class="keyword">if</span> (file.isDirectory())&#123;</span><br><span class="line">            System.out.println(path + folderName + <span class="string">&quot; 是一个目录&quot;</span>);</span><br><span class="line">        &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">            System.out.println(path + folderName + <span class="string">&quot; 不是一个目录&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 通过 字节流 向 指定文件 写入内容</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> fileName 文件名，这里为了简化，文件名中带上 路径</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">writeFileByByte</span><span class="params">(String fileName)</span></span>&#123;</span><br><span class="line">        File file = <span class="keyword">new</span> File(fileName);</span><br><span class="line">        OutputStream outputStream = <span class="keyword">null</span>; <span class="comment">// 从内存中 写入内容 到 文件中，这是输出流，因此要用 输出流</span></span><br><span class="line">        <span class="comment">// FileOutputStream 的构造器大体上有两类：一类是 传入一个带有文件名和文件路径的字符串；另一类是 传入一个 File 文件/文件夹对象</span></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            outputStream = <span class="keyword">new</span> FileOutputStream(file, <span class="keyword">true</span>); <span class="comment">// 给 file 文件对象 构造一个字节输出流</span></span><br><span class="line">        &#125; <span class="keyword">catch</span> (FileNotFoundException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 这里穿插一个小知识点，即我们 给一个 int 参数，但是我们要让 outputStream 以 byte[] 的形式写入,接下来就看 int 转 byte[] 吧</span></span><br><span class="line">        <span class="keyword">int</span> a = <span class="number">12345678</span>; <span class="comment">// 为什么这样呢？因为 一个 int 是 4个byte,所以一个 int 转成 byte[] 后，一定是里面包含4个byte元素的 byte[] 数组</span></span><br><span class="line">        <span class="keyword">byte</span>[] b = <span class="keyword">new</span> <span class="keyword">byte</span>[]&#123;</span><br><span class="line">                (<span class="keyword">byte</span>) ((a &gt;&gt; <span class="number">24</span>) &amp; <span class="number">0xFF</span>),</span><br><span class="line">                (<span class="keyword">byte</span>) ((a &gt;&gt; <span class="number">16</span>) &amp; <span class="number">0xFF</span>),</span><br><span class="line">                (<span class="keyword">byte</span>) ((a &gt;&gt; <span class="number">8</span>) &amp; <span class="number">0xFF</span>),</span><br><span class="line">                (<span class="keyword">byte</span>) ((a ) &amp; <span class="number">0xFF</span>)</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            outputStream.write(b); <span class="comment">// 这里还有一个问题没解决：写入的时候，选择编码格式(稍后解决)</span></span><br><span class="line">            outputStream.close();</span><br><span class="line">        &#125;<span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 通过 字节流 从 指定文件 读取输出内容</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> fileName 文件名，这里为了简化，文件名中带上 路径</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">readFileByByte</span><span class="params">(String fileName)</span></span>&#123;</span><br><span class="line">        File file = <span class="keyword">new</span> File(fileName);</span><br><span class="line">        InputStream inputStream = <span class="keyword">null</span>; <span class="comment">// 从 硬盘中 读取内容 到 内存中，这是 输入流，因此声明 输入流 对象</span></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            inputStream = <span class="keyword">new</span> FileInputStream(file);</span><br><span class="line">            <span class="comment">// inputStream 读取内容有5个方法 read():默认读取一个byte,readBytes(byte b[], int off, int len)</span></span><br><span class="line">            <span class="comment">// 这里我们采用 read(byte b[], int off, int len) 方法</span></span><br><span class="line">            <span class="keyword">byte</span>[] byter = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">1024</span>]; <span class="comment">// 所以先实例化一个 byte[]</span></span><br><span class="line">            <span class="keyword">int</span> len = inputStream.read(byter);</span><br><span class="line">            inputStream.close();</span><br><span class="line">            <span class="comment">// 最后我们输出一下读取到的内容</span></span><br><span class="line">            System.out.println(<span class="keyword">new</span> String(byter, <span class="number">0</span>, len));</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@author</span>: util.you.com@gmail.com</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span>: [sourceFile, desFile]</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span>: void</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@date</span>: 2019/5/25 18:04</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@version</span>: 1.0</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@description</span>: 最后来一个 从 指定文件中 读取内容 到 指定目标文件中</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">readWriteFile</span><span class="params">(String sourceFile, String desFile)</span></span>&#123;</span><br><span class="line">        File inputFile = <span class="keyword">new</span> File(sourceFile);</span><br><span class="line">        File outputFile = <span class="keyword">new</span> File(desFile);</span><br><span class="line">        InputStream inputStream = <span class="keyword">null</span>;</span><br><span class="line">        OutputStream outputStream = <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            inputStream = <span class="keyword">new</span> FileInputStream(inputFile);</span><br><span class="line">            <span class="keyword">byte</span>[] byter = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">1024</span>];</span><br><span class="line">            inputStream.read(byter);</span><br><span class="line">            outputStream = <span class="keyword">new</span> FileOutputStream(outputFile, <span class="keyword">true</span>);</span><br><span class="line">            outputStream.write(byter);</span><br><span class="line">            outputStream.close();</span><br><span class="line">            inputStream.close();</span><br><span class="line">            System.out.println(<span class="string">&quot;操作完成&quot;</span>);</span><br><span class="line">        &#125;<span class="keyword">catch</span> (Exception e)&#123;</span><br><span class="line">            System.out.println(e.getMessage());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">Author: </span><span class="post-copyright-info"><a href="mailto:undefined">Lorem Moon</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">Link: </span><span class="post-copyright-info"><a href="https://hello-github-ui.github.io/posts/65533/">https://hello-github-ui.github.io/posts/65533/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">Copyright Notice: </span><span class="post-copyright-info">All articles in this blog are licensed under <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> unless stating additionally.</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Java/">Java</a></div><div class="post_share"><div class="social-share" data-image="https://img.imgdb.cn/item/604b7e335aedab222ce6192e.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>Related Articles</span></div><div class="relatedPosts-list"><div><a href="/posts/49125/" title="BIO-NIO-AIO"><img class="cover" src="https://pic.imgdb.cn/item/60d18f04844ef46bb2bcb39a.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-06-22</div><div class="title">BIO-NIO-AIO</div></div></a></div><div><a href="/posts/32282/" title="Difference between FileReader vs FileInputStream in Java"><img class="cover" src="https://pic.imgdb.cn/item/616863312ab3f51d9106e681.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-10-26</div><div class="title">Difference between FileReader vs FileInputStream in Java</div></div></a></div><div><a href="/posts/53319/" title="Java中使用HSSFWorkbook生成excel"><img class="cover" src="https://pic.imgdb.cn/item/612111984907e2d39c4793a9.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2019-11-12</div><div class="title">Java中使用HSSFWorkbook生成excel</div></div></a></div><div><a href="/posts/62287/" title="Java代码实现裁剪图像"><img class="cover" src="https://pic.imgdb.cn/item/61503a642ab3f51d91207331.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-09-26</div><div class="title">Java代码实现裁剪图像</div></div></a></div><div><a href="/posts/10968/" title="Java代码的执行顺序"><img class="cover" src="https://pic.imgdb.cn/item/612110284907e2d39c445567.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-01-31</div><div class="title">Java代码的执行顺序</div></div></a></div><div><a href="/posts/17149/" title="Java实现批量重命名文件"><img class="cover" src="https://pic.imgdb.cn/item/61503f8a2ab3f51d91265312.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-09-26</div><div class="title">Java实现批量重命名文件</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> Comment</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://pic.imgdb.cn/item/6159d89b2ab3f51d91b0e8d0.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">Lorem Moon</div><div class="author-info__description">即已成过往，便随它而去吧。</div></div><div class="card-info-data is-center"><div class="card-info-data-item"><a href="/archives/"><div class="headline">Articles</div><div class="length-num">60</div></a></div><div class="card-info-data-item"><a href="/tags/"><div class="headline">Tags</div><div class="length-num">46</div></a></div><div class="card-info-data-item"><a href="/categories/"><div class="headline">Categories</div><div class="length-num">5</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/xxxxxx"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/hello-github-ui" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="mailto:util.you.come@gmail.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>Announcement</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>Catalog</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#java-IO-%E6%93%8D%E4%BD%9C%E5%88%86%E6%9E%90"><span class="toc-number">1.</span> <span class="toc-text">java IO 操作分析</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>Recent Post</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/posts/4723/" title="Redis主从搭建"><img src="https://pic.imgdb.cn/item/61210fda4907e2d39c439d0c.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Redis主从搭建"/></a><div class="content"><a class="title" href="/posts/4723/" title="Redis主从搭建">Redis主从搭建</a><time datetime="2022-03-08T12:34:42.574Z" title="Created 2022-03-08 20:34:42">2022-03-08</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/posts/43818/" title="Win10开启上帝模式"><img src="https://pic.imgdb.cn/item/621ddc1c2ab3f51d914c66cb.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Win10开启上帝模式"/></a><div class="content"><a class="title" href="/posts/43818/" title="Win10开启上帝模式">Win10开启上帝模式</a><time datetime="2022-03-08T12:24:42.000Z" title="Created 2022-03-08 20:24:42">2022-03-08</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/posts/55966/" title="Ubuntu修改静态IP"><img src="https://pic.imgdb.cn/item/621ddc1c2ab3f51d914c66cb.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Ubuntu修改静态IP"/></a><div class="content"><a class="title" href="/posts/55966/" title="Ubuntu修改静态IP">Ubuntu修改静态IP</a><time datetime="2022-03-04T16:11:25.000Z" title="Created 2022-03-05 00:11:25">2022-03-05</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/posts/42154/" title="Java封装同步锁"><img src="https://pic.imgdb.cn/item/621ddc1c2ab3f51d914c66cb.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Java封装同步锁"/></a><div class="content"><a class="title" href="/posts/42154/" title="Java封装同步锁">Java封装同步锁</a><time datetime="2022-03-02T12:50:01.000Z" title="Created 2022-03-02 20:50:01">2022-03-02</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/posts/1553/" title="初识大数据(一)"><img src="https://cdn.jsdelivr.net/gh/jerryc127/CDN@latest/cover/default_bg3.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="初识大数据(一)"/></a><div class="content"><a class="title" href="/posts/1553/" title="初识大数据(一)">初识大数据(一)</a><time datetime="2022-03-01T07:53:43.000Z" title="Created 2022-03-01 15:53:43">2022-03-01</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://img.imgdb.cn/item/604b7e335aedab222ce6192e.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2017 - 2022 By Lorem Moon</div><div class="framework-info"><span>Framework </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>Theme </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">Hi, welcome to my <a target="_blank" rel="noopener" href="https://hello-blogger-ui.blogspot.com/">google blog</a>!</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="Read Mode"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="Switch Between Light And Dark Mode"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="Toggle between single-column and double-column"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="Setting"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="Table Of Contents"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="Scroll To Comments"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="Back To Top"><i class="fas fa-arrow-up"></i></button></div></div><div id="algolia-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">Algolia</span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="search-wrap"><div id="algolia-search-input"></div><hr/><div id="algolia-search-results"><div id="algolia-hits"></div><div id="algolia-pagination"></div><div id="algolia-stats"></div></div></div></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.js"></script><script src="https://cdn.jsdelivr.net/npm/algoliasearch@4/dist/algoliasearch-lite.umd.js"></script><script src="https://cdn.jsdelivr.net/npm/instantsearch.js@4/dist/instantsearch.production.min.js"></script><script src="/js/search/algolia.js"></script><div class="js-pjax"><script>function loadValine () {
  function initValine () {
    const valine = new Valine(Object.assign({
      el: '#vcomment',
      appId: 'mFM6i90bN6KqyTH6tmC3q7dz-gzGzoHsz',
      appKey: 'T2tsKoiKjMaB0wgtIAgSz6Ul',
      avatar: 'monsterid',
      serverURLs: '',
      emojiMaps: "",
      path: window.location.pathname,
      visitor: false
    }, null))
  }

  if (typeof Valine === 'function') initValine() 
  else getScript('https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js').then(initValine)
}

if ('Valine' === 'Valine' || !false) {
  if (false) btf.loadComment(document.getElementById('vcomment'),loadValine)
  else setTimeout(loadValine, 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>